import pygit2
import os
import shutil
import errno
import stat
import sys
import threading
import queue

class GitClient():
    def __init__(self, git_url, username=None, password=None):
        self.git_url = git_url
        self.username = username
        self.password = password
        self.tmp_repo_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'tmp_repo')
        self.repo = None

    def get_branch(self):
        # 如果路径存在，先删除旧的仓库
        if os.path.exists(self.tmp_repo_dir):
            # 处理windows下PermissionError问题
            def handle_remove_read_only(func, path, exc):
                excvalue = exc[1]
                if func in (os.rmdir, os.remove, os.unlink) and excvalue.errno == errno.EACCES:
                    os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  # 0777
                    func(path)
                else:
                    sys.exit(1)
            shutil.rmtree(self.tmp_repo_dir, onerror=handle_remove_read_only)
        def _get_branch_task(result_queue):
            try:
                # 初始化裸仓库
                repo = pygit2.init_repository(self.tmp_repo_dir, bare=True)
                # 添加远程仓库
                remote = repo.remotes.create("origin", self.git_url)

                if self.username is None:
                    callbacks = pygit2.RemoteCallbacks()
                else:
                    # 设置认证回调
                    credentials = pygit2.UserPass(self.username, self.password)
                    callbacks = pygit2.RemoteCallbacks(credentials=credentials)
                # 拉取远程信息
                remote.fetch(callbacks=callbacks)
                # 获取远程分支名称
                refs = repo.listall_references()
                branch_list = [
                    ref.split("/")[-1] for ref in refs if ref.startswith("refs/remotes/origin/")
                ]
                result_queue.put({"status": "SUCCESS", "result": branch_list})
            except Exception as e:
                if "authentication" in str(e):
                    result_queue.put({"status": "ERROR", "result": "Git仓库认证失败！"})
                else:
                    result_queue.put({"status": "ERROR", "result": f"获取分支失败！错误：{e}"})

        result_queue = queue.Queue()
        thread = threading.Thread(target=_get_branch_task, args=(result_queue, ))
        thread.start()
        thread.join(timeout=15)
        if thread.is_alive():
            return {'status': 'ERROR', 'result': '访问Git仓库超时！'}
        else:
            return result_queue.get()

if __name__ == "__main__":
    import time
    git = GitClient("http://192.168.1.200:5580/root/web-demo.git", "root", "1234.com")
    #git = GitClient("https://gitee.com/zhenliangli/web-demo")
    print(git.get_branch())
